from os import name

import datetime
from datetime import timedelta
from venv import create
from dateutil import rrule
import re
from django.contrib.auth.models import User, Group, Permission, ContentType
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.decorators import login_required, permission_required
from django.utils.timezone import now
from django.db.models import Q
from rest_framework import filters
from rest_framework import permissions
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from django_filters.rest_framework import DjangoFilterBackend
# from rewrite.my_modelviewset import MyModelViewSet
from tool.paginations import CommonPagination
from .models import *
from .serializers import *
from common import restful
from common.my_modelviewset import MyModelViewSet
from common.my_mixins import MyListModelMixin, MyRetrieveModelMixin
# from common.paginations import CommonPagination

# from common.send_oa import SendOA
# from common.getuser import getuserdata

class BaseResponse(object):
    def __init__(self):
        self.code = 1000
        self.msg = ""
        self.data = None
        self.token = ""

    @property
    def dict(self):
        return self.__dict__

class LoginView(ObtainAuthToken):
    # 放行认证
    authentication_classes = ''
    permission_classes = ''

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,context={'request': request})
        # 如果设置raise_exception=True，则会终止请求，详见源码。
        serializer.is_valid(raise_exception=False)
        try:
            user = serializer.validated_data['user']
            token, create = Token.objects.get_or_create(user=user)
            print(token)
            groups = []
            for group in Group.objects.all():
                if user in group.user_set.all():
                    groups.append(group.id)
            data = {
                'token': token.key,
                'user_id': user.pk,
                'user_name': user.username,
                'name': user.extension.name,
                'perms': user.get_all_permissions(),
                'is_superuser': user.is_superuser,
                'user_sex':user.extension.sex,
                'user_grade':user.extension.grade.name,
                'user_role':user.extension.role.name,
                'groups': groups,
            }
            user.last_login = now()
            user.save()
            return restful.success('登录成功！', data)
        except KeyError:
            data = ''
            return restful.unauthorized('账号或密码错误，请重新尝试！', data)

class GroupOptionViewSet(MyModelViewSet):
    """
    权限分组下拉选
    """
    queryset = Group.objects.all()
    serializer_class = GradeOptionSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(MyModelViewSet):
    """
    用户分组<br>
    操作传参，不管是更新还是创建都需要提供<br>
    name：权限分组名<br>
    group_permission：权限ID数组列表<br>
    user_set：用户ID数组列表<br>
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

    def create(self, request, *args, **kwargs):
        """
        创建一个模型的实例.
        """
        # 截取未序列化数据
        group_permission = request.data['group_permission']
        users_items = request.data['user_set']

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 获取权限列表给分组赋予权限
        for permission in group_permission:
            if permission != '':
                permissions = Permission.objects.get(id=int(permission))
                # 遍历添加权限
                serializer.instance.permissions.add(permissions)
        serializer.save()
        # 获取用户列表给分组加入用户
        for user in users_items:
            if user != '':
                thisuser = User.objects.get(id=int(user))
                thisuser.groups.add(serializer.instance)
                thisuser.save()
        serializer.save()

        headers = self.get_success_headers(serializer.data)
        context = {
            'code': status.HTTP_201_CREATED,
            'msg': '创建成功！',
            'data': serializer.data
        }
        # ojm第一个修改点
        user = self.request.user

        return Response(context, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        """
        更新一个模型的实例.
        """
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        group_permission = []
        users_items = []
        if 'group_permission' in request.data:
            group_permission = request.data['group_permission']
        if 'user_set' in request.data:
            users_items = request.data['user_set']
        serializer = self.get_serializer(
            instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        if group_permission != []:
            # 清空之前的权限
            serializer.instance.permissions.clear()
            # 从新分配权限
            for permission in group_permission:
                if permission != '':
                    permissions = Permission.objects.get(id=int(permission))
                    # 遍历添加权限
                    serializer.instance.permissions.add(permissions)
        if users_items != []:
            # 清空在这个分组的所有用户
            all_user = User.objects.all()
            for this_user in all_user:
                this_user.groups.remove(serializer.instance)
                this_user.save()
            # 获取用户列表给分组加入用户
            for user in users_items:
                if user != '':
                    thisuser = User.objects.get(id=int(user))
                    thisuser.groups.add(serializer.instance)
                    thisuser.save()
        serializer.save()
        context = {
            'code': status.HTTP_200_OK,
            'msg': '更新成功！',
            'data': serializer.data
        }
        return Response(context)

    def destroy(self, request, *args, **kwargs):
        """
        销毁模型实例.
        """
        instance = self.get_object()
        # 永久删除
        self.perform_destroy(instance)
        context = {
            'code': status.HTTP_204_NO_CONTENT,
            'msg': '删除成功！',
            'data': ''
        }
        # 如果反馈“HTTP_204_NO_CONTENT”，会导致context中内容没有返回给浏览器
        return Response(context, status=status.HTTP_200_OK)


# 用户列表
class UserViewSet(MyModelViewSet):
    """
    用户列表（传参u_grade:用户班级，u_search:用户id/姓名/课程模糊查找，后期增加）
    """
    # queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]
    # 分页+统计
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]

    def create(self, request, *args, **kwargs):
        """
        创建一个模型的实例.
        """

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.validated_data['createdBy'] = request.user.username
        password = serializer.validated_data["password"]
        serializer.save()
        serializer.instance.set_password(password)
        if "username" in request.data:
            serializer.instance.username = request.data["username"]
        if "first_name" in request.data:
            serializer.instance.first_name = request.data["first_name "]
        if "last_name" in request.data:
            serializer.instance.last_name = request.data["last_name"]
        if "is_staff" in request.data:
            serializer.instance.is_staff = request.data["is_staff"]
        if "is_active" in request.data:
            serializer.instance.is_active = request.data["is_active"]
        if "group" in request.data:
            groups = request.data["group"]
            for group in groups:
                thisgroup = Group.objects.get(id=int(group))
                serializer.instance.groups.add(thisgroup)
        serializer.instance.save()
        if "name" in request.data:
            serializer.instance.extension.name = request.data["name"]
        if "sex" in request.data:
            serializer.instance.extension.sex = request.data["sex"]
        if "role" in request.data:
            serializer.instance.extension.role = Role.objects.get(
                id=int(request.data["role"]))
        if "grade" in request.data:
            serializer.instance.extension.grade = Grade.objects.get(
                id=int(request.data["grade"]))
        # 存放修改密码的时间
        # serializer.instance.extension.last_change_date = now()
        serializer.instance.extension.save()
        serializer.save()
        headers = self.get_success_headers(serializer.data)
        context = {
            'code': status.HTTP_201_CREATED,
            'msg': '创建成功！',
            'data': serializer.data
        }
        # ojm第一个修改点
        user = self.request.user
        obj = serializer.instance

        return Response(context, status=status.HTTP_201_CREATED, headers=headers)
   
    def update(self, request, *args, **kwargs):
        """
        更新一个模型的实例.
        """
        pk = kwargs.get('pk')
        partial = kwargs.pop('partial', False)
        # print('带引request对象的所有属性', request.__dict__)
        if pk == '0':
            instance = User.objects.filter(username=request.data.get('username')) .first() 
        else:
            instance = self.get_object()

        serializer = self.get_serializer(
            instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['lastEditedBy'] = request.user.username
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        context = {
            'code': status.HTTP_200_OK,
            'msg': '更新成功！',
            'data': serializer.data
        }

        return Response(context)

    # （ojm）用户搜索
    def get_queryset(self, *args, **kwargs):
        """
        通过获取搜索参数查找用户
        """
        search = self.request.query_params.get("u_search")
        grade = self.request.query_params.get("u_grade")

        #print("搜索内容：" + search)
        # 姓名
        if search == None and grade != None:
            if User.objects.filter(is_active=1).filter(extension__grade__name__icontains=grade).exists():
                return User.objects.filter(is_active=1).filter(extension__grade__name__icontains=grade)
            else:
                return User.objects.filter(is_active=1).order_by('-date_joined')

        elif grade == None and search != None:
            if User.objects.filter(is_active=1).filter(Q(extension__name__icontains=search) | Q(username__icontains=search) | Q(extension__role__name__icontains=search) | Q(extension__grade__name__icontains=search)).exists():
                return User.objects.filter(is_active=1).filter(Q(extension__name__icontains=search) | Q(username__icontains=search) | Q(extension__role__name__icontains=search) | Q(extension__grade__name__icontains=search))
            else:
                return User.objects.filter(is_active=1).order_by('-date_joined')

        elif grade != None and search != None:
            if User.objects.filter(is_active=1).filter(Q(extension__grade__name__icontains=grade) | Q(extension__name__icontains=search) | Q(username__icontains=search) | Q(extension__role__name__icontains=search) | Q(extension__grade__name__icontains=search)).exists():
                return User.objects.filter(is_active=1).filter(Q(extension__grade__name__icontains=grade) | Q(extension__name__icontains=search) | Q(username__icontains=search) | Q(extension__role__name__icontains=search) | Q(extension__grade__name__icontains=search))
            else:
                return User.objects.filter(is_active=1).order_by('-date_joined')
        else:
            return User.objects.filter(is_active=1).order_by('-date_joined')

    def destroy(self, request, *args, **kwargs):
        """
        销毁模型实例.
        """
        instance = self.get_object()
        # 永久删除
        self.perform_destroy(instance)
        context = {
            'code': status.HTTP_204_NO_CONTENT,
            'msg': '删除成功！',
            'data': ''
        }
        # 如果反馈“HTTP_204_NO_CONTENT”，会导致context中内容没有返回给浏览器
        return Response(context, status=status.HTTP_200_OK)

# 用户下拉选
class UserOptionViewSet(MyListModelMixin, viewsets.GenericViewSet):
    """
    用户下拉选
    """
    # queryset = User.objects.filter(is_active__exact='1')
    serializer_class = UserOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination

    def get_queryset(self, *args, **kwargs):
        """
        通过获取搜索参数查找用户
        """
        search = self.request.query_params.get("search")
        if search:
            return User.objects.filter(is_active__exact='1').filter(Q(username__exact=search) | Q(extension__name__icontains=search) | Q(extension__dept__name__icontains=search) | Q(extension__role__name__icontains=search))
        else:
            return User.objects.filter(is_active__exact='1')
  
#选课
class ScoreViews(MyModelViewSet):
    """
    选课-创建-显示
    """
    # queryset = Score.objects.all()
    serializer_class = ScoreSerializer
    permission_classes = [permissions.IsAuthenticated]
    # authentication_classes = ''
    # permission_classes = ''
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']

    def get_queryset(self):
        user = self.request.user
        user_course = Score.objects.filter(user=user.extension)
        return user_course
#岗位
class RoleViews(MyModelViewSet):

    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#岗位下拉选
class RoleOptionViews(MyModelViewSet):

    queryset = Role.objects.all()
    serializer_class = RoleOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#班级
class GradeViews(MyModelViewSet):

    queryset = Grade.objects.all()
    serializer_class = GradeSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#班级下拉选
class GradeOptionViews(MyModelViewSet):

    queryset = Grade.objects.all()
    serializer_class = GradeOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#课程
class CourseViews(MyModelViewSet):

    queryset = Course.objects.all()
    serializer_class = CourseSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    
    # def get_queryset(self, *args, **kwargs):
    #     user = self.request.user
    #     print('----------------------')
    #     print(user)
    #     course = Score.objects.filter(user=user.username)

    #     print('----------------------')
    #     print(course)
    #     if course:
    #         return course
    #     if score:
    #         return score
#课程下拉选
class CourseOptionViews(MyModelViewSet):

    queryset = Course.objects.all()
    serializer_class = CourseOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#作业
class HomeworkViews(MyModelViewSet):

    queryset = Homework.objects.all()
    serializer_class = HomeworkSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']

    
    
#作业下拉选
class HomeworkOptionViews(MyModelViewSet):

    queryset = Homework.objects.all()
    serializer_class = HomeworkOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#备注
# router.register(r'HomeworkCheckTask',Views.HomeworkCheckTask, basename='')
class HomeworkCheckTaskViews(MyModelViewSet):

    # queryset = HomeworkCheckTask.objects.all()
    serializer_class = HomeworkCheckTaskSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']

    def get_queryset(self):
        user = self.request.user
        user_homework = HomeworkCheckTask.objects.filter(runner=user.extension)
        return user_homework
    
#备注
class HomeworkCheckTaskOptionViews(MyModelViewSet):

    queryset = HomeworkCheckTask.objects.all()
    serializer_class = HomeworkCheckTaskOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#备注
# router.register(r'UserPortrait',Views.UserPortrait, basename='')
class UserPortraitViews(MyModelViewSet):

    queryset = UserPortrait.objects.all()
    serializer_class = UserPortraitSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#备注
class UserPortraitOptionViews(MyModelViewSet):

    queryset = UserPortrait.objects.all()
    serializer_class = UserPortraitOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#备注
# router.register(r'Portrait',Views.Portrait, basename='')
class PortraitViews(MyModelViewSet):

    queryset = Portrait.objects.all()
    serializer_class = PortraitSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#备注
class PortraitOptionViews(MyModelViewSet):

    queryset = Portrait.objects.all()
    serializer_class = PortraitOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#备注
# router.register(r'Images',Views.Images, basename='')
class ImagesViews(MyModelViewSet):

    queryset = Images.objects.all()
    serializer_class = ImagesSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#备注
class ImagesOptionViews(MyModelViewSet):

    queryset = Images.objects.all()
    serializer_class = ImagesOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#备注
# router.register(r'UserImage',Views.UserImage, basename='')
class UserImageViews(MyModelViewSet):

    queryset = UserImage.objects.all()
    serializer_class = UserImageSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#备注
class UserImageOptionViews(MyModelViewSet):

    queryset = UserImage.objects.all()
    serializer_class = UserImageOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#备注
# router.register(r'Files',Views.Files, basename='')
class FilesViews(MyModelViewSet):

    queryset = Files.objects.all()
    serializer_class = FilesSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#备注
class FilesOptionViews(MyModelViewSet):

    queryset = Files.objects.all()
    serializer_class = FilesOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    
#备注
# router.register(r'UserFile',Views.UserFile, basename='')
class UserFileViews(MyModelViewSet):

    queryset = UserFile.objects.all()
    serializer_class = UserFileSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    ## search_fields = ['name', 'user__username']
    
#备注
class UserFileOptionViews(MyModelViewSet):

    queryset = UserFile.objects.all()
    serializer_class = UserFileOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    # filterset_fields = ['id','name']
    # search_fields = ['name',]
    